package prj.carmap.mobile.activity;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import prj.carmap.mobile.CarmapApplication;
import prj.carmap.mobile.R;
import prj.carmap.mobile.activity.SellerListActivity.SellerListAdapter;
import prj.carmap.mobile.model.SearchCond;
import prj.carmap.mobile.model.SellerInfo;
import prj.carmap.mobile.model.SellerType;
import prj.carmap.mobile.process.AutoServiceProcess;
import prj.carmap.mobile.process.LiveServiceProcess;
import prj.carmap.mobile.util.AccessLogUtil;
import prj.carmap.mobile.util.ImgUtil;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviPara;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.miaowang.salad.activity.MineInfoActivity;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

/**
 * 商家列表界面
 *
 */
public class SellerListActivity extends SherlockActivity {

	private List<SellerInfo> sellers;
	//private boolean isInit = true;

	String[] sortItems = new String[] { "默认排序", "名字", "距离" };
	String[] rangeFilter = new String[] { "距离不限", "150米", "500米", "1000米", "3000米" };

	protected DialogView popView;
	private SearchCond searchCond = new SearchCond();
	private FilterAndSortHandler filterAndSortHandler;
	ListView listView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		CarmapApplication.addActivity(this);
		//Application app = (Application) this.getApplication();

		sellers = (List<SellerInfo>) this.getIntent().getExtras().get("sellers");
		setContentView(R.layout.activity_seller_list);

		// Inflate the custom view
		View customNav = LayoutInflater.from(this).inflate(R.layout.nav_seller_title_view, null);
		getSupportActionBar().setDisplayShowCustomEnabled(true);
		getSupportActionBar().setDisplayShowHomeEnabled(false);
		getSupportActionBar().setDisplayShowTitleEnabled(false);

		String title = this.getIntent().getExtras().getString("title");
		 final String typeId = this.getIntent().getStringExtra("sellerTypeId");
		((TextView) customNav.findViewById(R.id.nav_title)).setText("all".equals(title) ? "全部" : title);
		LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER);
		getSupportActionBar().setCustomView(customNav);
		customNav.setLayoutParams(lp);
		Button returnBtn = (Button) customNav.findViewById(R.id.return_prev);
		returnBtn.setOnClickListener(new Button.OnClickListener() {// 创建监听
					public void onClick(View v) {
						SellerListActivity.this.finish();
					}
				});

		Button mapBtn = (Button) customNav.findViewById(R.id.return_map);
		mapBtn.setOnClickListener(new Button.OnClickListener() {// 创建监听
			public void onClick(View v) {
				
				Intent in = new Intent(SellerListActivity.this, MapOverlayActivity.class);
				in.putExtra("typeId", typeId);
				in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				/*ArrayList<String> longitudeAarray = new ArrayList<String>();*/
				//ArrayList<String> latitudeAarray = new ArrayList<String>();
				/*ArrayList<String> nameAarray = new ArrayList<String>();
				ArrayList<String> sellerAarray = new ArrayList<String>();
				ArrayList<String> type = new ArrayList<String>();
				for(SellerInfo list:sellers){
					final double longitude = list.longitude;
					final double latitude = list.latitude;
					longitudeAarray.add(longitude+"");
					latitudeAarray.add(latitude+"");
					nameAarray.add(list.sellerName);
					sellerAarray.add(list.sellerId);
					type.add(list.superSellerType);
				}
				in.setClass(SellerListActivity.this, MapOverlayActivity.class);
				in.putStringArrayListExtra("longitudeAarray", longitudeAarray);
				in.putStringArrayListExtra("latitudeAarray", latitudeAarray);
				in.putStringArrayListExtra("nameAarray", nameAarray);
				in.putStringArrayListExtra("superSellerType", type);
				in.putStringArrayListExtra("sellerAarray", sellerAarray);*/
				/*Intent intent = new Intent(SellerListActivity.this, MapOverlayActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);*/
				SellerListActivity.this.startActivity(in);

			}
		});

		initMenuItem();

	//	Spinner spinnerSellerType = (Spinner) findViewById(R.id.seller_type_filter);
		List<String> typeNames = new ArrayList<String>();


		if (typeId != null) {
			if (CarmapApplication.sellerTypes != null) {
				for (SellerType type : CarmapApplication.sellerTypes) {
					if (type.children != null) {
						for (SellerType subType : type.children) {
							if (typeId.equals(subType.typeId + "")) {
								typeNames.add(type.typeName);
								break;
							}
						}
					}
				}
			}
			//spinnerSellerType.setEnabled(false);
		}
		else {
			typeNames.add("全部分类");
			if (CarmapApplication.sellerTypes != null) {
				CarmapApplication.getInstance();
				for (SellerType type : CarmapApplication.sellerTypes) {
					typeNames.add(type.typeName);
				}
			}
		}
		String[] sellerTypeFilter = typeNames.toArray(new String[0]);

		// 将可选内容与ArrayAdapter连接起来
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, rangeFilter);
		// 设置下拉列表的风格
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);


		listView = (ListView) findViewById(R.id.seller_list_view);
		listView.setAdapter(new SellerListAdapter(sellers));
		//String sellerType = this.getIntent().getStringExtra("sellerType");
		//String sellerName = this.getIntent().getStringExtra("sellerName");

		searchCond.sellerName = this.getIntent().getStringExtra("sellerName");
		searchCond.sellerTypeId = this.getIntent().getStringExtra("sellerTypeId");
		searchCond.lng = CarmapApplication.getInstance().getLocData().longitude;
		searchCond.lat = CarmapApplication.getInstance().getLocData().latitude;
		listView.setOnScrollListener(new SellerListScrollListener((SellerListAdapter) listView.getAdapter(), searchCond, this));
		filterAndSortHandler = new FilterAndSortHandler((SellerListAdapter) listView.getAdapter(), searchCond, this);
		//filterAndSortHandler.spinnerSellerType = spinnerSellerType;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		View view = (View) this.findViewById(R.id.menu_item_home);
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				AutoServiceProcess process = new AutoServiceProcess();
				process.setContext(SellerListActivity.this);
				process.getSellerTypes();
			}

		});
		
		view = (View) this.findViewById(R.id.menu_item_type);
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				LiveServiceProcess process = new LiveServiceProcess();
				process.setContext(SellerListActivity.this);
				process.getSellerTypes();
			}

		});

		view = (View) this.findViewById(R.id.menu_item_mine);
		view.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
//				UserInfo userInfo = CarmapApplication.getInstance().userInfo;
//				if (userInfo == null) {
//					SellerListActivity.this.startActivity(new Intent(
//							SellerListActivity.this, LoginActivity.class));
//				} else {
//					SellerListActivity.this.startActivity(new Intent(
//							SellerListActivity.this, ProfileActivity.class));
//				}
				SellerListActivity.this.startActivity(new Intent(
						SellerListActivity.this, MineInfoActivity.class));
			}

		});

		return super.onCreateOptionsMenu(menu);
	}

	@SuppressWarnings("deprecation")
	private void initMenuItem() {
		if ("type".equals(CarmapApplication.currentPage)) {
			// 底部菜单项
			View menuItem = this.findViewById(R.id.menu_item_type);
			menuItem.setBackgroundDrawable(getApplication().getResources().getDrawable(R.drawable.bottom_background));
			// 底部菜单图标
			ImageView itemImage = (ImageView) this.findViewById(R.id.item_type_image);
			itemImage.setImageResource(R.drawable.type_select);
			// 底部菜单文字
			TextView itemText = (TextView) this.findViewById(R.id.item_type_text);
			itemText.setTextColor(getApplication().getResources().getColor(R.color.white));
		}
//		else if ("search".equals(CarmapApplication.currentPage)) {
//			// 底部菜单项
//			View menuItem = this.findViewById(R.id.menu_item_search);
//			menuItem.setBackgroundDrawable(getApplication().getResources().getDrawable(R.drawable.bottom_background));
//			// 底部菜单图标
//			ImageView itemImage = (ImageView) this.findViewById(R.id.item_search_image);
//			itemImage.setImageResource(R.drawable.search_select);
//			// 底部菜单文字
//			TextView itemText = (TextView) this.findViewById(R.id.item_search_text);
//			itemText.setTextColor(getApplication().getResources().getColor(R.color.white));
//		}
		else if ("mine".equals(CarmapApplication.currentPage)) {
			// 底部菜单项
			View menuItem = this.findViewById(R.id.menu_item_mine);
			menuItem.setBackgroundDrawable(getApplication().getResources().getDrawable(R.drawable.bottom_background));
			// 底部菜单图标
			ImageView itemImage = (ImageView) this.findViewById(R.id.item_mine_image);
			itemImage.setImageResource(R.drawable.mine_select);
			// 底部菜单文字
			TextView itemText = (TextView) this.findViewById(R.id.item_mine_text);
			itemText.setTextColor(getApplication().getResources().getColor(R.color.white));
		}
		else if ("salad".equals(CarmapApplication.currentPage)) {
			// 底部菜单项
			View menuItem = this.findViewById(R.id.menu_item_salad);
			menuItem.setBackgroundDrawable(getApplication().getResources()
					.getDrawable(R.drawable.bottom_background));
			// 底部菜单图标
			ImageView itemImage = (ImageView) this
					.findViewById(R.id.item_salad_image);
			itemImage.setImageResource(R.drawable.mine_select);
			// 底部菜单文字
			TextView itemText = (TextView) this
					.findViewById(R.id.item_salad_text);
			itemText.setTextColor(getApplication().getResources().getColor(
					R.color.white));
		}
/*		else if ("more".equals(CarmapApplication.currentPage)) {
			// 底部菜单项
			View menuItem = this.findViewById(R.id.menu_item_home);
			menuItem.setBackgroundDrawable(getApplication().getResources().getDrawable(R.drawable.bottom_background));
			// 底部菜单图标
			ImageView itemImage = (ImageView) this.findViewById(R.id.item_home_image);
			itemImage.setImageResource(R.drawable.more_select);
			// 底部菜单文字
			TextView itemText = (TextView) this.findViewById(R.id.item_home_text);
			itemText.setTextColor(getApplication().getResources().getColor(R.color.white));
		}*/
	}

	public class SellerListAdapter extends BaseAdapter {
		List<SellerInfo> sellerItems = new ArrayList<SellerInfo>();

		public SellerListAdapter(List<SellerInfo> list) {
			addSellerInfo(list);
		}

		public void addSellerInfo(List<SellerInfo> list) {
			for (int i = 0; i < list.size(); i++) {
				sellerItems.add(list.get(i));
			}
		}

		public void resetAndAddSellerInfo(List<SellerInfo> list) {
			sellerItems.clear();
			for (int i = 0; i < list.size(); i++) {
				sellerItems.add(list.get(i));
			}
		}

		@Override
		public int getCount() {
			return sellerItems.size();
		}

		@Override
		public Object getItem(int position) {
			return sellerItems.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			return makeView(sellerItems.get(position), position);
		}

		private View makeView(final SellerInfo seller, int position) {
			LayoutInflater inflater = (LayoutInflater) SellerListActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View itemView = inflater.inflate(R.layout.listitem_seller, null);
			try {
			View layout = itemView.findViewById(R.id.list_seller_layout);
//			LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER);
//			params.setMargins(10, 10, 10, 0);
//			layout.setLayoutParams(params);

			layout.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					CarmapApplication.popView = new DialogView(SellerListActivity.this);
					CarmapApplication.popView.show();
					SellerListScrollListener.client.get(
							CarmapApplication.SERVER_URL + "/rest/seller/" + seller.sellerId,
							new AsyncHttpResponseHandler() {
								public void onSuccess(String content) {
									try
									{
										JSONObject json = new JSONObject(content);
										Intent intent = new Intent(SellerListActivity.this, SellerActivity.class);
										intent.putExtra("currentSeller", SellerInfo.fromJson(json));
										intent.putExtra("flag", CarmapApplication.currentPage);
										SellerListActivity.this.startActivity(intent);
									}
									catch (JSONException e) {
										e.printStackTrace();
									}
									CarmapApplication.popView.hide();
								}
							});
				};
			});

			TextView name = (TextView) itemView.findViewById(R.id.seller_name);
			name.setText((position + 1) + "." + seller.sellerName);
			TextView distance = (TextView) itemView.findViewById(R.id.distance);
			distance.setText(formatDistance(seller.distance));
			TextView address = (TextView) itemView.findViewById(R.id.seller_address);
			address.setText("地址："+seller.address);
			TextView call = (TextView) itemView.findViewById(R.id.seller_phone);
			call.setText("电话："+seller.telephone);
			ImageView sellerPic = (ImageView) itemView.findViewById(R.id.seller_img);
			final View loading = (View) itemView.findViewById(R.id.seller_img_loading);
			
			//ImageLoader imageLoader = new ImageLoader();
		
			
				ImgUtil.loadImage(sellerPic, CarmapApplication.SERVER_URL + "/images/" + seller.sellerPic,new SimpleImageLoadingListener(){
					
					 public void onLoadingStarted(String imageUri, View view) {
						 loading.setVisibility(View.VISIBLE);
					 }
					 
					 public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
						 loading.setVisibility(View.GONE);
					 }
					 @Override
					public void onLoadingFailed(String imageUri, View view,
							FailReason failReason) {
						 loading.setVisibility(View.GONE);
					}
					
				},SellerListActivity.this);
			//	imageLoader.showImageAsyn(sellerPic, CarmapApplication.SERVER_URL + "/images/" + seller.sellerPic, loading, R.drawable.no_seller_pic);
			

			View callSeller = (View) itemView.findViewById(R.id.call_seller_image);
			final String phone = seller.telephone;
			callSeller.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (phone == null || "".equals(phone.trim())) {
						return;
					}
					new AlertDialog.Builder(SellerListActivity.this)
							.setTitle(R.string.confirm_call)
							.setMessage("拨打电话" + phone + "?")
							.setPositiveButton(R.string.submit,
									new android.content.DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog, int which) {
											Intent phoneIntent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + phone));
											SellerListActivity.this.startActivity(phoneIntent);
											//发送拨打电话log给服务器
											StringEntity log = AccessLogUtil.createAccessLogParam(seller.sellerId, phone);
											if (log != null)
												new AsyncHttpClient().post(SellerListActivity.this, CarmapApplication.SERVER_URL + "/rest/accesslog", log, "application/json", new AsyncHttpResponseHandler());
										}
									}).setNegativeButton(R.string.cancel, null)
							.show();
				}
			});


			View goSeller = (View) itemView.findViewById(R.id.go_seller_image);
			final double longitude = seller.longitude;
			final double latitude = seller.latitude;
			goSeller.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					SellerListActivity.this.startNavi(v, latitude, longitude);
				}
			});
			} catch (Exception e) {
				e.printStackTrace();
			}
			return itemView;
		}

		private String formatDistance(int distance) {
			if (distance > 1000)
			{
				double dis = distance / 1000d;
				DecimalFormat df = new DecimalFormat("########0.0");
				return df.format(dis) + "千米";
			}
			else
			{
				return distance + "米";
			}
		}
	}

	
	/**
	 * 开始导航
	 *
	 * @param view
	 */
	public void startNavi(View view, double targetLat, double targetLon) {
		int lat = (int) (CarmapApplication.getInstance().getLocData().latitude * 1E6);
		int lon = (int) (CarmapApplication.getInstance().getLocData().longitude * 1E6);
		GeoPoint pt1 = new GeoPoint(lat, lon);
		lat = (int) (targetLat * 1E6);
		lon = (int) (targetLon * 1E6);
		GeoPoint pt2 = new GeoPoint(lat, lon);
		Intent intent = new Intent(this, RoutePlanActivity.class);
		intent.putExtra("startPosLat", pt1.getLatitudeE6());
		intent.putExtra("startPosLng", pt1.getLongitudeE6());
		intent.putExtra("endPosLat", pt2.getLatitudeE6());
		intent.putExtra("endPosLng", pt2.getLongitudeE6());
		this.startActivity(intent);

		/*// 构建 导航参数
		NaviPara para = new NaviPara();
		para.startPoint = pt1;
		para.startName = "从这里开始";
		para.endPoint = pt2;
		para.endName = "到这里结束";

		try {
			BaiduMapNavigation.openBaiduMapNavi(para, this);
		}
		 catch (BaiduMapAppNotSupportNaviException e) {
			e.printStackTrace();
			startWebNavi(view, targetLat, targetLon);
		}*/
	}

	public void startWebNavi(View view, double targetLat, double targetLon) {
		int lat = (int) (CarmapApplication.getInstance().getLocData().latitude * 1E6);
		int lon = (int) (CarmapApplication.getInstance().getLocData().longitude * 1E6);
		GeoPoint pt1 = new GeoPoint(lat, lon);
		lat = (int) (targetLat * 1E6);
		lon = (int) (targetLon * 1E6);
		GeoPoint pt2 = new GeoPoint(lat, lon);
		// 构建 导航参数
		NaviPara para = new NaviPara();
		para.startPoint = pt1;
		para.endPoint = pt2;
		BaiduMapNavigation.openBaiduMapNavi(para, this);
	}

	class RangeSpinnerListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos, long total) {
			filterAndSortHandler.filterAndSort();
		}

		public void onNothingSelected(AdapterView<?> arg0) {
		}
	}

	class TypeSpinnerListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos, long total) {
			filterAndSortHandler.filterAndSort();
		}

		public void onNothingSelected(AdapterView<?> arg0) {
		}
	}

	class SortSpinnerListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos, long total) {
			filterAndSortHandler.filterAndSort();
		}

		public void onNothingSelected(AdapterView<?> arg0) {
		}
	}

	public static StringEntity createStringEntity(JSONObject jsonParams) {
		try {
			StringEntity entity = new StringEntity(jsonParams.toString(), "utf-8");
			return entity;
		}
		catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
}

class FilterAndSortHandler extends AsyncHttpResponseHandler {
	static AsyncHttpClient client = new AsyncHttpClient();
	public SellerListAdapter adapter;
	public Spinner spinnerRange;
	public Spinner spinnerSellerType;
	public Spinner spinnerSort;
	private SearchCond searchCond;
	private Context context;
	private DialogView popView;
	int count = 0;
	Integer[] ranges = new Integer[] { Integer.MAX_VALUE, 150, 500, 1000, 300 };

	public FilterAndSortHandler(SellerListAdapter adapter, SearchCond searchCond, Context context) {
		this.adapter = adapter;
		this.searchCond = searchCond;
		this.context = context;
	}

	public void filterAndSort() {
		if (count < 2) {
			count++;
			return;
		}

		JSONObject jsonParams = new JSONObject();
		try
		{
			searchCond.start = 0;
			int pos = spinnerRange.getSelectedItemPosition();
			searchCond.distance = ranges[pos];
			if(spinnerSellerType!=null){
			pos = spinnerSellerType.getSelectedItemPosition();
			if (spinnerSellerType.isEnabled() == false)
			{
				//从类型选择画面迁移过来,类型不可选择
				searchCond.sellerTypeId = ((SellerListActivity) context).getIntent().getStringExtra("sellerTypeId");
			}
			else
			{
				if (pos == 0) {
					searchCond.sellerTypeId = 0 + "";
				}
				else
				{
					CarmapApplication.getInstance();
					if (CarmapApplication.sellerTypes != null) {
						CarmapApplication.getInstance();
						searchCond.sellerTypeId = CarmapApplication.sellerTypes.get(pos - 1).typeId + "";
					}
				}
			}
			}
			pos = spinnerSort.getSelectedItemPosition();
			if (pos == 0 || pos == 2) {
				searchCond.sortKey = "distance";
			}
			else {
				searchCond.sortKey = "name";
			}

			jsonParams.put("sellerName", searchCond.sellerName);
			jsonParams.put("start", searchCond.start);
			jsonParams.put("sellerTypeId", searchCond.sellerTypeId);
			jsonParams.put("sortKey", searchCond.sortKey);
			jsonParams.put("distance", searchCond.distance);
			jsonParams.put("lng", searchCond.lng);
			jsonParams.put("lat", searchCond.lat);
			popView = new DialogView(context);
			popView.show();
			client.post(context,
					CarmapApplication.SERVER_URL + "/rest/seller/page", SellerListActivity.createStringEntity(jsonParams),
					"application/json", this);
		}
		catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public void onSuccess(String content) {
		try
		{
			JSONArray jsonAry = new JSONArray(content);
			ArrayList<SellerInfo> sellers = new ArrayList<SellerInfo>();
			for (int i = 0; i < jsonAry.length(); i++) {
				JSONObject json = jsonAry.getJSONObject(i);
				sellers.add(SellerInfo.fromJson(json));
			}
			((SellerListActivity) context).listView.scrollTo(0, 0);
			adapter.resetAndAddSellerInfo(sellers);
			adapter.notifyDataSetChanged();
		}
		catch (JSONException e) {
			e.printStackTrace();
		}
		popView.hide();
	}

	public void onFailure(Throwable error, String content) {
		popView.hide();
	}
}

class SellerListScrollListener extends AsyncHttpResponseHandler implements OnScrollListener {
	int lastVisibleIndex = 0;
	static AsyncHttpClient client = new AsyncHttpClient();
	public SellerListAdapter adapter;
	public SearchCond searchCond;
	public Context context;
	public boolean doing;
	private DialogView popView;

	public SellerListScrollListener(SellerListAdapter adapter,
			SearchCond searchCond, Context context) {
		this.searchCond = searchCond;
		this.adapter = adapter;
		this.context = context;
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// 计算最后可见条目的索引
		lastVisibleIndex = firstVisibleItem + visibleItemCount - 1;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// 滑到底部后自动加载，判断listview已经停止滚动并且最后可视的条目等于adapter的条目
		adapter = (SellerListAdapter) view.getAdapter();
		if (!doing && scrollState == OnScrollListener.SCROLL_STATE_IDLE
				&& lastVisibleIndex == view.getAdapter().getCount() - 1) {
			searchCond.start = view.getAdapter().getCount();
			try
			{
				JSONObject jsonParams = new JSONObject();
				jsonParams.put("sellerName", searchCond.sellerName);
				jsonParams.put("start", searchCond.start);
				jsonParams.put("sellerTypeId", searchCond.sellerTypeId);
				jsonParams.put("sortKey", searchCond.sortKey);
				jsonParams.put("distance", searchCond.distance);
				jsonParams.put("lng", searchCond.lng);
				jsonParams.put("lat", searchCond.lat);
				popView = new DialogView(context);
				popView.show();
				client.post(context,
						CarmapApplication.SERVER_URL + "/rest/seller/page", SellerListActivity.createStringEntity(jsonParams),
						"application/json", this);
			}
			catch (Exception ex) {
			}
		}

	}

	public void onSuccess(String content) {
		try
		{
			JSONArray jsonAry = new JSONArray(content);
			ArrayList<SellerInfo> sellers = new ArrayList<SellerInfo>();
			if (jsonAry.length() > 0)
			{
				for (int i = 0; i < jsonAry.length(); i++)
				{
					JSONObject json = jsonAry.getJSONObject(i);
					sellers.add(SellerInfo.fromJson(json));
				}
				adapter.addSellerInfo(sellers);
				adapter.notifyDataSetChanged();
			}
			else
			{
				if (adapter.getCount() > 10) {
					Toast.makeText(context, "已经到最后了。", Toast.LENGTH_SHORT).show();
				}
			}
			doing = false;
		}
		catch (JSONException e) {
			e.printStackTrace();
		}

		popView.hide();
	}

	public void onFailure(Throwable error, String content) {
		popView.hide();
	}

}
